<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>统一认证中心</title>
    <link href="./css/style.css" rel="stylesheet" />
    <link href="./css/swiper-bundle.min.css" rel="stylesheet" />
    <script src="./js/polyfill.min.js"></script>
    <script src="./js/babel.min.js"></script>
    <script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>
    <script src="./js/jquery-3.4.1.min.js"></script>
    <script src="./js/swiper-bundle.min.js"></script>
    <script src="./js/jsencrypt.js"></script>
  </head>
  <body>
    <div class="login-box">
      <div class="logo">
        <img
          class="logobg"
          src="./images/logo.png"
          alt="中国建筑第七工程局有限公司"
        />
      </div>
      <div class="logo">
        <img class="logoimg" alt="logo" />
        <div class="titleBox">
          <div class="titleCH"></div>
          <div class="titleEN"></div>
        </div>
      </div>
      <div class="login">
        <ul class="tab">
          <li id="tab1" data-type="account">账户登录</li>
          <li id="tab2" data-type="ddlogin">扫码登录</li>
        </ul>
        <div class="tab-cont account">
          <form id="accountLogin" name="accountLogin">
            <div class="inputbox">
              <div class="tit">账号</div>
              <input
                type="text"
                name="username"
                id="username"
                placeholder="用户名"
                maxlength="50"
              />
            </div>
            <div class="error-tip"></div>
            <div class="inputbox">
              <div class="tit">密码</div>
              <input
                type="password"
                name="password"
                id="password"
                placeholder="账户密码"
                maxlength="50"
              />
            </div>
            <div class="error-tip"></div>
            <div id="verify_div" class="inputbox ver" style="display:none">
              <input
                class="verify"
                type="text"
                name="verify"
                id="verify"
                placeholder="验证码"
                maxlength="50"
              />
              <img class="verify-img" src="" id="verify-img" alt="验证码" />
            </div>
            <div class="error-tip"></div>
          </form>
          <!-- <div class="operate">
                    <div class="left flex">
                        <div class="check-box">
                            <span class="check-box-inner"></span>
                        </div>
                        <div class="check-txt">记住账号</div>
                    </div>
                </div> -->
          <button id="toLogin">登 录</button>
          <div id="loginErr" class="error-tip"></div>
        </div>
        <div class="tab-cont ddlogin">
          <div class="qrcode-content">
            <div class="qrcode-img">
              <div id="ddQrcode" class="qrcode"></div>
              <img class="qrcode-tips" src="./images/scan-img.png" />
            </div>
          </div>
          <div class="error-tip">账号或密码错误，请重新登录！</div>
          <p class="flex flex-a-c desc">
            <img class="scan-ico" src="./images/scan-ico.png" /> 打开<span
              class="blue"
              >钉钉 APP</span
            >扫码登录
          </p>
        </div>
      </div>
      <!-- <video
        id="video"
        autoplay
        muted
        loop
        poster="./images/bg.jpg"
        src="./images/bg.mp4"
        x5-video-player-type="h5"
        playsinline
        webkit-playsinline
      ></video> -->
      <div class="video">
        <div class="swiper-wrapper">
          <!-- <div class="swiper-slide">
            <img src="./reviews/智能制造.png" alt="" />
          </div> -->
          <div class="swiper-slide">
            <div class="swiper-bg init-bg"></div>
          </div>
        </div>
      </div>
    </div>
    <script type="text/babel">
      $(function () {
        var pathRoot = "";
        try {
          var currentPath = document.location.href;
          var staticIdx = currentPath.indexOf("static");
          pathRoot = currentPath.substring(0, staticIdx - 1);
        } catch (err) {
          console.log("error" + err);
        }
        function getQueryVariable(variable) {
          const query = window.location.search.substring(1);
          const vars = query.split("&");

          for (let i = 0; i < vars.length; i++) {
            const pair = vars[i].split("=");
            if (pair[0] === variable) {
              return pair[1];
            }
          }
          return false;
        }
        function getLoginCfg() {
          const imageBase64ToBlob = (urlData, type = "image/jpeg") => {
            try {
              const mime = type;
              // 去掉url的头，并转化为byte
              const bytes = window.atob(urlData);
              // 处理异常,将ascii码小于0的转换为大于0
              const ab = new ArrayBuffer(bytes.length);
              // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
              const ia = new Uint8Array(ab);

              for (let i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i);
              }

              return new Blob([ab], {
                type: mime,
              });
            } catch (e) {
              const ab = new ArrayBuffer(0);
              return new Blob([ab], {
                type: type,
              });
            }
          };
          // 获取登陆页面配置
          $.get(pathRoot + "/usercenter-admin-app/admin/sysCarousel", (res) => {
            if (res.code === 0) {
              document.title = res.data.sloganCn;
              $(".titleCH").html(res.data.sloganCn);
              $(".titleEN").html(res.data.sloganEn);
              // 如果有logo，则显示logo
              if (res.data.logoBase64) {
                $(".logoimg")
                  .attr(
                    "src",
                    URL.createObjectURL(
                      imageBase64ToBlob(
                        res.data.logoBase64,
                        res.data.logoSuffix.replace(".", "image/")
                      )
                    )
                  )
                  .show();
              }
              // 背景轮播
              if (
                res.data.carouselList &&
                Array.isArray(res.data.carouselList)
              ) {
                res.data.carouselList.map((d) => {
                  const src = URL.createObjectURL(
                    imageBase64ToBlob(
                      d.fileBase64,
                      d.fileSuffix.replace(".", "image/")
                    )
                  );
                  $(".swiper-wrapper").append(`
                    <div class="swiper-slide">
                        <div class="swiper-bg" style="background-image:url(${src})"></div>
                    </div>
                `);
                });
                // 图片轮播
                new Swiper(".video", {
                  loop: res.data.carouselList.length > 1,
                  autoplay: {
                    delay: 2000,
                  },
                  speed: 500,
                });
              }
            }
          });
          // 获取登陆项配置
          $.get(pathRoot + "/doGetLoginType", (res) => {
            console.log(res);
            if (res.code === 0) {
              const codeData = getQueryVariable("code");
              if (res.data.accountSecret) {
                $("#tab1").show();
                $(".tab li").first().click();
                //   if (!codeData) {
                //     $(".tab li").first().click();
                //   }
              }
              if (res.data.dingDing) {
                $("#tab2").show();
                if (codeData) {
                  $(".tab li").last().click();
                }
                initDD(codeData);
              }
            }
          });
        }
        // 钉钉扫码登录
        function initDD(codeData) {
          // 钉钉登录后回调
          if (codeData) {
            $(".ddlogin").find(".error-tip").css("opacity", 0);
            // 获取到授权码
            console.log("获取到授权码", codeData);
            $.ajax({
              type: "GET",
              url: pathRoot + "/doLogin2",
              data: { code: codeData },
              dataType: "json",
              success: ({ code, data, message }) => {
                // 登录成功，可以跳转到需要的页面
                if (code === 0) {
                  // window.location.reload()
                  window.location.href = data.redirectUrl;
                  return;
                } else {
                  $(".ddlogin").find(".error-tip").css("opacity", 1);
                }
              },
            });
          }
          // 钉钉登录
          var url = encodeURIComponent(window.location.href);
          // 测试
          // var goto = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoao18fpsm90erp4x0y&response_type=code&scope=snsapi_login&state=STATE&redirect_uri='+url
          // 正式
          var goto =
            "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoap53mtp7nmjn1nxsy&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=" +
            url;
          var obj = DDLogin({
            id: "ddQrcode", //这里需要你在自己的页面定义一个HTML标签并设置id，例如<div id="login_container"></div>或<span id="login_container"></span>
            goto: encodeURIComponent(goto), //请参考注释里的方式
            style: "border:none;background-color:transparent;",
            width: "260",
            height: "380",
          });
          var handleMessage = function (event) {
            var origin = event.origin;
            console.log("origin", event.origin);
            if (origin == "https://login.dingtalk.com") {
              //判断是否来自ddLogin扫码事件。
              var loginTmpCode = event.data; //拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了
              console.log("loginTmpCode", loginTmpCode);
              if (loginTmpCode) {
                const getUrl = `${goto}&loginTmpCode=${loginTmpCode}`;
                window.location.href = getUrl;
              }
            }
          };
          if (typeof window.addEventListener != "undefined") {
            window.addEventListener("message", handleMessage, false);
          } else if (typeof window.attachEvent != "undefined") {
            window.attachEvent("onmessage", handleMessage);
          }
        }
        function getVerifyImg() {
          const url = pathRoot + "/getCaptcha?t=" + Date.now();
          const xhr = new XMLHttpRequest();
          xhr.open("GET", url, true);
          xhr.responseType = "blob";
          // xhr.setRequestHeader("client_type", "DESKTOP_WEB");
          // xhr.setRequestHeader(
          //   "desktop_web_access_key",
          //   _desktop_web_access_key
          // );
          xhr.onload = function () {
            if (this.status == 200) {
              const blob = this.response;
              try {
                $("#verify-img").attr("src", window.URL.createObjectURL(blob));
              } catch (error) {
                $("#verify-img").attr("src", blob);
              }
              // img.src = window.URL.createObjectURL(blob);
              // $("#imgcontainer").html(img);
            }
          };
          xhr.send();
          // $.ajax({
          //   url: pathRoot + "/getCaptcha",
          //   dataType: "blob",
          //   responseType: "blob",
          //   xhrFields: { responseType: "blob" },
          //   success: (res) => {
          //     console.log(res);
          //     if (res) {
          //       try {
          //         $("#verify-img").attr(
          //           "src",
          //           window.URL.createObjectURL(stream)
          //         );
          //       } catch (error) {
          //         $("#verify-img").attr("src", res);
          //       }
          //     }
          //   },
          // });
        }
        var redirectUrl = getQueryVariable("redirect_url");
        redirectUrl = redirectUrl ? redirectUrl : "";
        var toUrl = getQueryVariable("to_url");
        toUrl = toUrl ? toUrl : "";

        $("#verify-img").click(function () {
          getVerifyImg();
        });
        // 获取登陆配置数据
        getLoginCfg();
        //首次登录不展示校验码
        // 获取验证码
        //getVerifyImg();
        // tab切换交互
        $(".tab li").click(function () {
          $(this).addClass("cur").siblings().removeClass("cur");
          var type = $(this).attr("data-type");
          $(".tab-cont").hide();
          $("." + type).show();
        });
        // 记住密码选择
        // $('.operate .left').click(function(){
        //     var _this = $(this)
        //     if(_this.hasClass('active')){
        //         _this.removeClass('active')
        //     }else{
        //         _this.addClass('active')
        //     }
        // })
        function handleLogin() {
          // 获取表单值
          var username = $("#username").val(),
            password = $("#password").val(),
            verify = $("#verify").val();
          //加密密码
          var encrypt = new JSEncrypt();
          var rsaPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAnB61jk1TvjPxJzwsmPFDQiZJj6lWAXK3bTkVS8qfmFjABXvkzRwaIN9N3Mh7Oetw4eOzI+0yQ/uiXxkJIdLzdTOiRsBwZtuife+QfAimirWE5yJJOemkmM3fFWLXNWWxtIboekFQdL9WCNqP+PmB7p90HVmMyyfkehU3ID+IEQIDAQAB";
          encrypt.setPublicKey(rsaPublicKey);
          password = encrypt.encrypt(password);
          $(".error-tip").css("opacity", 0);
          if (!username) {
            $("#username")
              .parent(".inputbox")
              .next(".error-tip")
              .text("用户名不能为空")
              .css("opacity", 1);
            return;
          }
          if (!password) {
            $("#password")
              .parent(".inputbox")
              .next(".error-tip")
              .text("密码不能为空")
              .css("opacity", 1);
            return;
          }
          if (!verify && $("#verify_div")[0].style.display == 'block') {//验证码不隐藏时判空
            $("#verify")
              .parent(".inputbox")
              .next(".error-tip")
              .text("验证码不能为空")
              .css("opacity", 1);
            return;
          }
          // var ifRemember = $('.operate .left').hasClass('active')
          $.ajax({
            type: "GET",
            url: pathRoot + "/doLogin2",
            data: {
              username,
              password,
              redirectUrl,
              toUrl,
              captchaCode: verify,
            },
            dataType: "json",
            success: ({ code, data, message }) => {
              // 登录成功，可以跳转到需要的页面
              if (code === 0) {
                // window.location.reload()
                window.location.href = data.redirectUrl;
                return false;
              }
              if (message) {
                $("#loginErr").text(message).css("opacity", 1);
                //首次登录失败获取验证码
                getVerifyImg();
                //首次登录失败显示验证码
                $("#verify_div").show();
              }
            },
          });
        }
        // 账号登录表单提交逻辑
        // 表单校验
        $("#toLogin").click(function () {
          handleLogin();
        });
        // 监听enter
        $(window).keydown(function (event) {
          // const event = ev || event;
          if (event.keyCode == 13) {
            event.preventDefault();
            handleLogin();
          }
        });
      });
    </script>
  </body>
</html>
